from SoftwareStarter_UI import Ui_SoftwareStarter_Main
from PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout, QVBoxLayout, QToolButton, QSizePolicy, QPushButton, QGroupBox, QGridLayout
from PyQt5.QtGui import QIcon, QFont, QPixmap
from PyQt5.QtCore import QPoint, QRect, QSize, Qt  # , pyqtSignal
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5 import QtWidgets, QtCore
from PyQt5 import QtGui
# PySide2
# PyQt5
import sys
import os
from os import environ, listdir, makedirs, pathsep, startfile
from PyQt5 import QtCore, QtGui, QtWidgets

import xml.dom.minidom
class mainWindow(Ui_SoftwareStarter_Main, QMainWindow):
    def __init__(self):
        super(mainWindow, self).__init__()
        self.setupUi(self)
        self.flowLayout = FlowLayout()
        self.ProjecStart()

    def ProjecStart(self):
        allProjecpath = "H:\RareWolf_Toolkit\project_info\project"
        #allProjecpath = "H:\RareWolf_Toolkit\pipeline_tools\SoftwareStarter\Projecinfo"
        for i in os.listdir(allProjecpath):
            f = open(allProjecpath + "/" + i, "r")
            r = f.read()
            text = str(r.encode('utf-8'), encoding="utf-8")
            DOMTree = xml.dom.minidom.parseString(text)
            collection = DOMTree.documentElement
            #self.Read_projectSettings(collection)
            self.Start_Settings(collection)

    def Read_projectSettings(self,collection):
        ProjectName = collection.getElementsByTagName('ProjectName')[0].getAttribute('Settinginput')
        #print(ProjectName)
        ProjectNameCH = collection.getElementsByTagName('ProjectNameCH')[0]

        #print(ProjectNameCH.childNodes[0].nodeValue)#项目名
        '''
        Redshift = collection.getElementsByTagName('Redshift')[0]
        print (Redshift.childNodes[0].nodeValue +"\t#获取子节点 值")
        '''
        #项目列表按钮
        item = QtWidgets.QListWidgetItem(ProjectNameCH.childNodes[0].nodeValue)

        item.setTextAlignment(QtCore.Qt.AlignLeading | QtCore.Qt.AlignVCenter)
        font = QtGui.QFont()
        font.setPointSize(20)
        item.setFont(font)
        brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.NoBrush)
        item.setBackground(brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.NoBrush)
        item.setForeground(brush)
        self.Project_listWidget.addItem(item)

    ###按钮函数
    def Start_Settings(self,collection):
        #删除按钮控件
        for i in range(self.flowLayout.count()):
            self.flowLayout.itemAt(i).widget().deleteLater()
        Software = "Maya"
        try:
            employees= collection.getElementsByTagName("Project_" + Software + '_Start')
            buttonName = employees[0].getAttribute(Software + '_name')
            #print(buttonName)
            environ = os.environ.copy()
            list = employees[0].getAttribute('script_id')
            script_id_list = list.split(",")
            for script_id in script_id_list:
                #print(script_id)
                for employee in employees:
                    ageNode = employee.getElementsByTagName(script_id)[0]
                    environ[script_id] = ageNode.childNodes[0].nodeValue
            launch_path = employee.getElementsByTagName("MAYA_DefaultPath")[0].childNodes[0].nodeValue
            print (launch_path)
            self.Start_buttton(buttonName,launch_path,environ)
        except:
            print("软件启动未添加")

    ###启动按钮执行
    def Start_buttton_Run(self,launch_path,environ):
        import subprocess
        subprocess.Popen(launch_path,env=environ)

    ###创建按钮
    def Start_buttton(self,buttonName,launch_path,environ):
        self.button = QPushButton()
        self.button.setObjectName(buttonName)
        self.button.setText(buttonName)
        self.button.setGeometry(QtCore.QRect(10, 10, 100, 100))
        self.button.setMinimumSize(QtCore.QSize(100, 100))
        #self.button.clicked.connect(lambda *args: self.Start_buttton_Run(launch_path,environ))
        #self.button.mouseDoubleClickEvent(lambda *args: self.Start_buttton_Run(launch_path,environ))
        self.button.mouseDoubleClickEvent = lambda event: self.onDoubleClick(event, buttonName,launch_path,environ)
        self.flowLayout.addWidget(self.button)
        self.SoftwareStartup_listWidget.setLayout(self.flowLayout)

    # 在此处执行双击事件的操作
    def onDoubleClick(self, event, btn_text,launch_path,environ):
        if event.button() == Qt.LeftButton:
            print(f"Double-clicked on {btn_text}")
            self.Start_buttton_Run(launch_path,environ)



class FlowLayout(QLayout):
    def __init__(self, parent=None, margin=0, spacing=-1):
        super(FlowLayout, self).__init__(parent)

        if parent is not None:
            self.setContentsMargins(margin, margin, margin, margin)

        self.setSpacing(spacing)

        self.itemList = []

    def __del__(self):
        item = self.takeAt(0)
        while item:
            item = self.takeAt(0)

    def addItem(self, item):
        self.itemList.append(item)

    def count(self):
        return len(self.itemList)

    def clear(self):  # real signature unknown; restored from __doc__
        """ clear(self) -> None """
        self.itemList.clear()

    def itemAt(self, index):
        if index >= 0 and index < len(self.itemList):
            return self.itemList[index]

        return None

    def deleteLater(self):  # real signature unknown; restored from __doc__
        """ deleteLater(self) """
        pass

    def takeAt(self, index):
        if index >= 0 and index < len(self.itemList):
            return self.itemList.pop(index)

        return None

    def expandingDirections(self):
        return Qt.Orientations(Qt.Orientation(0))

    def hasHeightForWidth(self):
        return True

    def heightForWidth(self, width):
        height = self.doLayout(QRect(0, 0, width, 0), True)
        return height

    def setGeometry(self, rect):
        super(FlowLayout, self).setGeometry(rect)
        self.doLayout(rect, False)

    def sizeHint(self):
        return self.minimumSize()

    def minimumSize(self):
        size = QSize()

        for item in self.itemList:
            size = size.expandedTo(item.minimumSize())

        margin, _, _, _ = self.getContentsMargins()

        size += QSize(2 * margin, 2 * margin)
        return size

    def doLayout(self, rect, testOnly):
        x = rect.x()
        y = rect.y()
        lineHeight = 0

        for item in self.itemList:
            wid = item.widget()
            spaceX = self.spacing() + wid.style().layoutSpacing(QSizePolicy.PushButton,
                                                                QSizePolicy.PushButton, Qt.Horizontal)
            spaceY = self.spacing() + wid.style().layoutSpacing(QSizePolicy.PushButton,
                                                                QSizePolicy.PushButton, Qt.Vertical)
            nextX = x + item.sizeHint().width() + spaceX
            if nextX - spaceX > rect.right() and lineHeight > 0:
                x = rect.x()
                y = y + lineHeight + spaceY
                nextX = x + item.sizeHint().width() + spaceX
                lineHeight = 0

            if not testOnly:
                item.setGeometry(QRect(QPoint(x, y), item.sizeHint()))

            x = nextX
            lineHeight = max(lineHeight, item.sizeHint().height())

        return y + lineHeight - rect.y()
if __name__ == '__main__':
    app = QApplication([]) if not QApplication.instance() else None
    MWin = mainWindow()
    for qt in QApplication.topLevelWidgets():
        if qt.windowTitle() == u'MainWindow':
            qt.close()
    MWin.show()
    app.exec_() if app else None